import datetime
import random
import string
from websockets.asyncio.server import ServerConnection
from multiprocessing import Queue
import tkinter as tk
import base64
import re

from typing import Dict


def generate_time_message() -> str:
    """生成包含北京时间和 UTC 时间的消息"""
    utc_time = datetime.datetime.now(datetime.UTC)
    beijing_time = utc_time.astimezone(datetime.timezone(datetime.timedelta(hours=8)))
    return f"{beijing_time.isoformat()} ({utc_time.isoformat()})"


def get_connection_status_message(websocket: ServerConnection, is_new=True) -> str:
    current_time = datetime.datetime.now().strftime("%H:%M:%S")

    client_address_str = get_client_address_str(websocket)
    # client_address_str最长长度计算：ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:65535, 长度为 39 + 1 + 5 = 45
    if is_new:
        return f"{current_time} - ({client_address_str.center(45)}) 🟢已连接"
    else:
        return f"{current_time} - ({client_address_str.center(45)}) 🟤已断开"


def get_client_address_str(websocket: ServerConnection):
    client_ip, client_port = websocket.remote_address[:2]
    client_address_str = f"{client_ip}:{client_port}"
    return client_address_str


def generate_color_combinations():
    # foreground_colors = [31, 32, 33, 34, 35, 36]  # 红/绿/黄/蓝/紫/青
    # background_colors = [40, 47]  # 黑/灰
    # styles = [0, 4]  # 显示方式

    # color_combinations = []

    # # 生成前景色、背景色和显示方式的所有组合
    # for fg in foreground_colors:
    #     for bg in background_colors:
    #         for style in styles:
    #             # 跳过黄色前景 (33) + 灰色背景 (47) 的组合, 因为看不清
    #             if not (bg == 47 and fg == 33):
    #                 color_combinations.append((fg, bg, style))

    # random.seed(1)
    # random.shuffle(color_combinations)

    # fmt: off
    color_combinations = [(36, 40, 4), (32, 40, 4), (34, 47, 4), (33, 40, 4), (36, 47, 0), (36, 47, 4), (34, 40, 4), (34, 47, 0), (31, 40, 0), (35, 47, 0), (31, 40, 4), (35, 47, 4), (32, 47, 0), (34, 40, 0), (32, 47, 4), (35, 40, 0), (35, 40, 4), (31, 47, 4), (33, 40, 0), (31, 47, 0), (36, 40, 0), (32, 40, 0)]
    # fmt: on
    return color_combinations


def connections2str(connections: set):
    color_combinations = generate_color_combinations()

    # 将集合转换为列表并排序
    sorted_connections = sorted(connections, key=lambda x: id(x))

    # 构建输出字符串
    output = []
    for connection in sorted_connections:
        connection_id = id(connection)
        # 根据连接的 id 计算颜色组合索引
        color_index = connection_id % len(color_combinations)
        fg_color, bg_color, under_line = color_combinations[color_index]
        color_code = f"\033[{under_line};{fg_color};{bg_color}m"
        output.append(f"{color_code}{connection_id}\033[0m")  # 重置颜色为默认

    formatted_output = "{" + ", ".join(output) + "}"
    return formatted_output


def queue_print(queue_print_queue: Queue, text):
    """打印到控制台, 并将文本放入队列"""
    print(text)

    # 确保处理的是字符串
    text = str(text)

    # 去掉ANSI颜色代码
    cleaned_text = re.sub(r"\033\[[0-9;]*m", "", text)
    # 替换长连续空白字符
    cleaned_text = re.sub(r"\s{3,}", "  ", cleaned_text)

    # 将文本放入队列
    if queue_print_queue is not None:
        queue_print_queue.put(cleaned_text)


def set_window_icon_from_base64(root: tk.Tk, base64_icon=None):
    """
    设置 tkinter 窗口图标, 图标数据以 Base64 编码形式传递。

    :param root: Tk() 实例或 Toplevel() 实例
    :param base64_icon: Base64 编码的图标数据, 可选(默认为简单的 GIF 图标)
    """
    # 默认的 Base64 编码 GIF 图标数据
    default_icon = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAdZJREFUeF7tmk1OwzAQhWeg7FFPkEoUiVtwlHaZXgJ6Cbpsb8IxkACpOUHEnipGgU1rBM+OQf7J6/b5Z+abN04qR2XkPx15/kIAdMDICbAFRm4AHoJsAbbAyAmwBVwMcLl5qs7k4k5MdyuilcucdMaYxog2Rg/Lt/qmseOCDvhM3kz26SQ0PJJODzMbAgQw3bxuxZjF8G0Tmqly39bz9XFEGMDDi0koheBQ2tX8JGdvAPYCwRH98wJTq4AEQAewBf72DEA9lroefAimniCKjwDQUwgRzF0PdgACGFtHBSIAVCFEEM2PraP46QBUIUTQ1u317Hdv3/XQ/ND9gh1AAODvMqpgqE4HWAR8gQa3ADpDYuvozCEAVCFEEM2PraP46QBUIUTQV0f7Id33kEPxBTsAbYDeE1DCoY85FB8BoAoggr462g/pybUACji2jgoU3AKxE0T7EwBvhk7vNgdcjT3v8/sm4KfGME27up4dq/gMKOp6XHdtfbX0AvD1gcT5Y/4u+F79HgR0QD+oh6BmslUxVZYgVHedvK8HfSKDHjO5604OyD3J3+IngJKr65IbHeBCqeQxdEDJ1XXJjQ5woVTyGDqg5Oq65EYHuFAqeQwdUHJ1XXL7AKF/3lBxkE7hAAAAAElFTkSuQmCC"

    # 如果用户没有提供 base64_icon, 使用默认值
    if base64_icon is None:
        base64_icon = default_icon

    try:
        # 解码 Base64 数据为二进制
        decoded_icon = base64.b64decode(base64_icon)
    except Exception as e:
        raise ValueError(
            "Failed to decode Base64 data. Please check the input data."
        ) from e

    try:
        # 将二进制数据加载为 PhotoImage 对象
        icon = tk.PhotoImage(data=decoded_icon)
    except Exception as e:
        raise ValueError(
            "Failed to load the icon image. Please ensure it's a valid image format."
        ) from e

    try:
        # 设置窗口图标
        root.tk.call("wm", "iconphoto", root._w, icon)
    except Exception as e:
        raise ValueError(
            "Failed to set the window icon. Please check if the window is properly initialized."
        ) from e

    return icon


def dict_to_hotkey_str(hotkey_dict: Dict[str, str]):
    """将字典转换为快捷键配置字符串"""
    lines = []
    for key, value in hotkey_dict.items():
        lines.append(f"{key}: {value}")
    return "\n".join(lines)


def hotkey_str_to_dict(s: str):
    """
    将包含快捷键配置的字符串解析为字典。
    支持中英文冒号作为分隔符。
    """
    hotkey_dict = {}
    lines = s.strip().split("\n")
    for line in lines:
        line = line.strip()
        if not line:
            continue
        # 处理中英文冒号
        if ":" in line:
            parts = line.split(":", 1)
        elif "：" in line:
            parts = line.split("：", 1)
        else:
            continue  # 忽略无效行
        if len(parts) != 2:
            continue
        key, value = parts[0].strip(), parts[1].strip()
        hotkey_dict[key] = value
    return hotkey_dict


def generate_random_hotkey_str():
    """生成随机的合法快捷键字符串"""
    modifiers = ["<ctrl>", "<alt>", "<shift>", "<cmd>"]
    normal_keys = [
        "a",
        "b",
        "c",
        "d",
        "e",
        "f",
        "g",
        "h",
        "i",
        "j",
        "k",
        "l",
        "m",
        "n",
        "o",
        "p",
        "q",
        "r",
        "s",
        "t",
        "u",
        "v",
        "w",
        "x",
        "y",
        "z",
        "<f1>",
        "<f2>",
        "<f3>",
        "<f4>",
        "<f5>",
        "<f6>",
        "<f7>",
        "<f8>",
        "<f9>",
        "<f10>",
        "<f11>",
        "<f12>",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "0",
        "-",
        "=",
        "[",
        "]",
        "\\",
        ";",
        "'",
        ",",
        ".",
        "/",
        "`",
        "<enter>",
        "<tab>",
        "<space>",
        "<backspace>",
        "<delete>",
        "<up>",
        "<down>",
        "<left>",
        "<right>",
        "<home>",
        "<end>",
        "<page_up>",
        "<page_down>",
    ]

    # 随机选择修饰键
    num_modifiers = random.randint(0, 3)
    selected_modifiers = (
        random.sample(modifiers, num_modifiers)
        if num_modifiers <= len(modifiers)
        else []
    )

    # 随机选择普通键并处理
    normal_key = random.choice(normal_keys)
    if len(normal_key) == 1 and normal_key.isalpha() and random.random() < 0.5:
        normal_key = random.choice(string.ascii_lowercase)
    elif normal_key.startswith("<f"):
        normal_key = f"<f{random.randint(1, 12)}>"

    # 构建快捷键字符串
    parts = selected_modifiers + [normal_key]
    return "+".join(parts)


def generate_random_hotkey_dict(num_entries=3):
    """
    生成包含随机快捷键配置的字典
    """
    hotkey_dict = {}

    for _ in range(num_entries):
        key = generate_random_hotkey_str()
        value = f"这是一条消息{random.choice(string.ascii_uppercase)}!"
        hotkey_dict[key] = value
    return hotkey_dict


def generate_random_hotkeys():
    s = dict_to_hotkey_str(generate_random_hotkey_dict())
    return s


def open_project_homepage():
    """打开项目主页"""
    import webbrowser

    url = "https://gitee.com/beibeibeibei/SuperK"
    webbrowser.open(url)
